#coding=utf-8
import cv2
import time
#cap = cv2.VideoCapture(0)
print u'请输入要处理的视频文件路径:'
videoFile = raw_input()
cap = cv2.VideoCapture(str(videoFile))
cap.set(5,100)

if cap.isOpened() == False:
    print "open cap 0 fail"

fourcc = cv2.VideoWriter_fourcc(*'XVID')
out = cv2.VideoWriter('D:/video/analy.avi', fourcc, 20.0,(300,240))
fgbg = cv2.createBackgroundSubtractorKNN()
kernel1 = cv2.getStructuringElement(cv2.MORPH_CROSS, (10, 10))
while True:
    result,frame = cap.read()
    #frame = cv2.transpose(frame)
    #frame = cv2.flip(frame,0)

    frameBat = frame.copy()
    fgmask = fgbg.apply(frame)

    rect, fgmask = cv2.threshold(fgmask, 137, 255, cv2.THRESH_BINARY)
    fgmask = cv2.erode(fgmask, kernel1, iterations=1)# 腐蚀
    fgmask = cv2.dilate(fgmask, kernel1,iterations=1)#膨胀

    image, contours, hierarchy = cv2.findContours(fgmask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)  # 提取轮廓

    for c in contours:
        arec = cv2.contourArea(c)
        if arec > 200 and arec < 100000:
            #print arec

            frameBat = cv2.resize(frameBat, (300,240), interpolation=cv2.INTER_AREA)  # 转换时间长
            out.write(frameBat)

    #frame = cv2.resize(frame, (240,300), interpolation=cv2.INTER_AREA)  # 转换时间长

    cv2.imshow("result",frame)
    #time.sleep(0.06)
    cv2.waitKey(1)

